package com.itlong.cloud.controller.sdkV1.cloud.elevator.server;

import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.RobotNoninductiveDeviceUniqueVO;
import com.itlong.cloud.POJO.VO.sdk.RobotNoninductiveHistoryRecordVO;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudElevarotErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKRobotClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      机器人无感SDK controller
 * </desc>
 *
 * @createDate 2019/07/16
 */
@RestController
@RequestMapping("/cloud/elevator/rtl")
public class RobotNoninductiveController {

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    ICloudElevatorSDKRobotClient iCloudElevatorSDKRobotClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;
    /**
     * <desc>
     *      根据设备唯一码查询电梯信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2019/07/17
     */
    @ResponseBody
    @PostMapping("/getElevatorInfos")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ELEVATOR_INFO_LOG_DESC)
    public Object getElevatorInfos(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKServerElevatorKeyDTO cloudElevatorSDKServerElevatorKeyDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKServerElevatorKeyDTO.class, request);
            String projectId = cloudElevatorSDKServerElevatorKeyDTO.getProjectId();

            if (StringUtils.isBlank(cloudElevatorSDKServerElevatorKeyDTO.getDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验证机器人是否有权限
            if (iCloudTalkSDKServerUserServiceClient.checkRobot(cloudElevatorSDKServerElevatorKeyDTO.getAppId(),cloudElevatorSDKServerElevatorKeyDTO.getAppSecret(),cloudElevatorSDKServerElevatorKeyDTO.getRobotId()) == 0) {
                return new MessageVO(CloudElevarotErrorCodeEnum.ROBOT_AUTH_ERROR.getErrorCode());
            }
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKServerElevatorKeyDTO.getProjectId() + "查询项目下电梯设备唯一码列表");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            List<String> deviceUniques = iCloudElevatorSDKRobotClient.getElevatorKey(cloudElevatorSDKServerElevatorKeyDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            List<String> deviceUniqueParams = StringHandlerUtil.splitStringList(cloudElevatorSDKServerElevatorKeyDTO.getDeviceUnique());
            for (String deviceUniqueParam : deviceUniqueParams) {
                if (!deviceUniques.contains(deviceUniqueParam)) {
                    return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),deviceUniqueParam);
                }
            }
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
            cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(cloudElevatorSDKServerElevatorKeyDTO.getDeviceUnique());
            List<RobotNoninductiveDeviceUniqueVO> cloudElevatorSDKGetByDeviceUniqueVOS = iCloudElevatorSDKServerCloudServiceClient.getElevatorInfoForRobot(cloudElevatorSDKGetByDeviceUniqueDTO);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "根据设备唯一码" + cloudElevatorSDKServerElevatorKeyDTO.getDeviceUnique() + "查询电梯信息");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),cloudElevatorSDKGetByDeviceUniqueVOS);
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK_服务端_根据设备唯一码查询电梯信息】根据设备唯一码查询电梯信息失败",e);
        }
    }

    /**
     * <desc>
     *      呼叫电梯
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @RequestMapping(value = "/call",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_ROBOT_CALL_ELEVATOR)
    @ResponseBody
    public Object callElevator() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            RobotNoninductiveCallDTO cloudElevatorSDKCallElevatorDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(RobotNoninductiveCallDTO.class, request);
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            String deviceUnique = iCloudElevatorSDKServerCloudServiceClient.getDeviceUniqueByControllerDeviceUnique(cloudElevatorSDKCallElevatorDTO.getControllerDeviceUnique());
            if(StringUtils.isBlank(deviceUnique)){
                return new MessageVO(CloudElevarotErrorCodeEnum.CONTROLLER_NOT_FOUND.getErrorCode());
            }
            deviceUnique = StringHandlerUtil.splitString(deviceUnique)[0];
            //查询电梯设备是否绑定控制器
            Map<String,Object> controller = iAppDeviceServiceClient.getControllerDeviceUniqueByElevatorDeviceUnique(deviceUnique);
            String isOnline;
            //判断群控器是否在线
            if(controller != null && controller.get("groupConId") != null){
                isOnline = iIotServerServiceClient.batchGetDeviceState(controller.get("iotProductKey").toString(),controller.get("groupConId").toString());
                if(isOnline ==null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))){
                    return new MessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode());
                }
            }
            //删除呼梯结果缓存
            redisService.delForDevice(RedisConstant.REDIS_IOT_CLOUD_CONTROLLER_NOTIFY_MESSAGE_CACHE +
                    cloudElevatorSDKCallElevatorDTO.getControllerDeviceUnique()+cloudElevatorSDKCallElevatorDTO.getRobotId());
            //获取真实楼层
            Map<String,Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(cloudElevatorSDKCallElevatorDTO.getToFloor(),cloudElevatorSDKCallElevatorDTO.getFromFloor(),
                    deviceUnique);
            if(floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null){
                return new MessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode());
            }
            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(deviceUnique,
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("fromFloor").toString(),floor.get("goFloor").toString(),null,
                    CloudElevatorCallTypeEnum.OUT.getType(),null,CallElevatorSourceTypeEnum.ROBOT.getType(),cloudElevatorSDKCallElevatorDTO.getRobotId(),null,null, 1, cloudElevatorSDKCallElevatorDTO.getUpDown(), null, "");
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",cloudElevatorSDKCallElevatorDTO.getProjectId() + "呼叫电梯");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(cloudElevatorSDKCallElevatorDTO.getControllerDeviceUnique());
            saveDTO.setFromFloor(floor.get("fromNaturalFloor").toString());
            saveDTO.setToFloor(floor.get("goNaturalFloor").toString());
            saveDTO.setProjectId(cloudElevatorSDKCallElevatorDTO.getProjectId());
            saveDTO.setUserId(cloudElevatorSDKCallElevatorDTO.getRobotId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.ROBOT.getType());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_SDKgetElevatorKey】呼叫电梯异常", e);
        }
    }


    /**
     * <desc>
     *      获取群控器呼梯结果信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2019/07/17
     */
    @ResponseBody
    @PostMapping("/getCallInfo")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_CONTROLLER_NOTIFY_MESSAGE_DESC)
    public Object getCallInfo(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            RobotNoninductiveGetCallInfoVO robotNoninductiveGetCallInfoVO = HttpProtocolUtil.parseRequestParamToDTO(RobotNoninductiveGetCallInfoVO.class, request);
            String projectId = robotNoninductiveGetCallInfoVO.getProjectId();

            if (StringUtils.isBlank(robotNoninductiveGetCallInfoVO.getControllerDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String deviceUnique = iCloudElevatorSDKServerCloudServiceClient.getCallInfo(robotNoninductiveGetCallInfoVO.getRobotId(),robotNoninductiveGetCallInfoVO.getControllerDeviceUnique());
            Map<String,Object> data = new HashMap<>();
            data.put("deviceUnique",deviceUnique);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "根据设备唯一码" + robotNoninductiveGetCallInfoVO.getControllerDeviceUnique() + "查询群控器呼梯结果信息");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),data);
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK_服务端_根据设备唯一码查询群控器呼梯结果信息】根据设备唯一码查询群控器呼梯结果信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取群控器呼梯记录
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2019/07/17
     */
    @ResponseBody
    @PostMapping("/historyCallRecord")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_CONTROLLER_NOTIFY_MESSAGE_DESC)
    public Object historyCallRecord(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            RobotNoninductiveHistoryRecordDTO recordDTO = HttpProtocolUtil.parseRequestParamToDTO(RobotNoninductiveHistoryRecordDTO.class, request);
            Page<RobotNoninductiveHistoryRecordVO> page= iCloudElevatorSDKServerCloudServiceClient.getHistoryRecords(recordDTO);
            //保存生成操作日志所需信息 详细描述和接口类别
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        } catch (Exception e) {
            throw new DataAccessException("【云电梯SDK_服务端_获取群控器呼梯记录】获取群控器呼梯记录失败",e);
        }
    }
}
